package cn.dapeng.interview;

import cn.dapeng.util.SleepingUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 实现一个容器，提供两个方法 add和size
 * 写两个线程 线程1添加10个元素，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束??
 * <p>
 * <p>
 * <p>
 * 这种写法实现不了
 */
public class Taobao_Wait_Notify {

    private List<Integer> list = Collections.synchronizedList(new ArrayList<>());

    public void add(int num) {
        list.add(num);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {


        Taobao_Wait_Notify taobao = new Taobao_Wait_Notify();


        Object lock = new Object();

        new Thread(() -> {
            synchronized (lock) {
                if (taobao.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("t2 end");
                lock.notify();
            }
        }).start();

        SleepingUtil.sleep(1, TimeUnit.SECONDS);

        new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    taobao.add(i);
                    System.out.println("add" + i);
                    if (taobao.size() == 5) {
                        lock.notify();

                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }

        }).start();


    }
}
